package top.tagao.ref_05_getObjectNew;

import org.junit.Test;
import top.tagao.ref_05_getObjectNew.service.Person;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;

/**
 * @author fu-xiao-liu
 * @Date 2022/3/25 18:46
 * 获取运行时类的方法结构
 */
public class MethodGetObjectNew {


    @Test
    public void test01() {
        Class clazz = Person.class;
        //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
        Method[] methods = clazz.getMethods();
        for (Method m : methods) {
            System.out.println(m);
        }
        System.out.println();
        //getDeclaredMethods():获取当前运行时类中声明的所有方法。（不包含父类中声明的方法）
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m : declaredMethods) {
            System.out.println(m);
        }
    }


    /**
     * @date 权限修饰符  返回值类型  方法名(参数类型1 形参名1,...) throws XxxException{}
     */
    @Test
    public void test02() {
        Class clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {

            //.权限修饰符
            System.out.print("权限修饰符为 "+Modifier.toString(  method.getModifiers()) + "\t");

            //. 方法名
            System.out.print("方法名为 " + method.getName() + " ");

            //. 获取方法声明的注解
            Annotation[] annotations = method.getAnnotations();
            Stream.of(annotations).forEach( s-> System.out.print(" "+ s));

            //. 返回值类型
            System.out.print("返回值为 " + method.getReturnType().getName() + "\t");



            //.获取形参
            Class<?>[] parameterTypes = method.getParameterTypes();
            System.out.print("(");
            if(!(parameterTypes == null && parameterTypes.length == 0)){
                for(int i = 0;i < parameterTypes.length;i++){

                    if(i == parameterTypes.length - 1){
                        System.out.print(parameterTypes[i].getName() + " args_" + i);
                        break;
                    }

                    System.out.print(parameterTypes[i].getName() + " args_" + i + ",");
                }
            }
            System.out.print(")");



            //6.抛出的异常
            Class[] exceptionTypes = method.getExceptionTypes();
            if(exceptionTypes.length > 0){
                System.out.print("throws ");
                for(int i = 0;i < exceptionTypes.length;i++){
                    if(i == exceptionTypes.length - 1){
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }

                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }


            System.out.println();
        }
    }
}